<?php

class PlateTrackerTable extends Doctrine_Table
{
  public static function findMy()
  {
    if (!($userId = myUser::id()))
    {
      return array();
    }

    return Doctrine_Query::create()->select('pt.*')
      ->addSelect('(SELECT COUNT(*) FROM Message m WHERE m.recipient_plate = pt.plate) num')
      ->addSelect('(SELECT COUNT(*) FROM Message m2 WHERE m2.recipient_plate = pt.plate AND m2.created_at > pt.viewed_at) not_seen')
      ->from('PlateTracker pt')->where('pt.user_id = ?', $userId)
      ->execute();
  }

  public static function updatedMy($plates = array())
  {
    if (!$plates || !($userId = myUser::id()))
    {
      return false;
    }

    $query = Doctrine_Query::create()->update('PlateTracker')->set('viewed_at', '?', date('Y-m-d H:i:s'))
      ->where('user_id = ?', $userId);

    if (!is_array($plates))
    {
      $query->andWhere('plate = ?', $plates);
    }
    else
    {
      $query->andWhereIn('plate', $plates);
    }

    return $query->execute();
  }

  public static function isTracked($plate)
  {
    if (!$plate || !($userId = myUser::id()))
    {
      return false;
    }

    return (bool)Doctrine_Query::create()->select('user_id')->from('PlateTracker')
      ->where('user_id = ? AND plate = ?', array($userId, $plate))
      ->execute(null, Doctrine::HYDRATE_SINGLE_SCALAR);
  }
}
